package com.atguigu.srb.core.controller.api;


import com.atguigu.srb.common.result.R;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.pojo.entity.LendItem;
import com.atguigu.srb.core.pojo.vo.InvestVO;
import com.atguigu.srb.core.service.LendItemService;
import com.atguigu.srb.core.service.TransFlowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 标的出借记录表 前端控制器
 * </p>
 *
 * @author Mr.bilal
 * @since 2023-07-18
 */
@RestController
@RequestMapping("/api/core/lendItem")
public class ApiLendItemController {

    @Autowired
    LendItemService lendItemService;

    @Autowired
    TransFlowService transFlowService;


    @GetMapping("/getLendItemList/{lendNo}")
    public R getLendItemList(HttpServletRequest request,@PathVariable String lendNo){
        List<LendItem> lendItemList =  lendItemService.getLendItemList(lendNo);
        return R.ok().data("lendItemList",lendItemList);

    }

    @GetMapping("/getInterestCount/{investAmount}/{lendYearRate}/{period}/{returnMethod}")
    public R getInterestCount(@PathVariable BigDecimal investAmount,@PathVariable BigDecimal lendYearRate,@PathVariable Integer period,@PathVariable Integer returnMethod){
        BigDecimal interestCount = lendItemService.getInterestCount(investAmount,lendYearRate,period,returnMethod);
        return R.ok().data("interestCount",interestCount);
    }

    @PostMapping("/commitInvest")
    public R commitInvest(@RequestBody InvestVO investVO, HttpServletRequest request){
        String userId = request.getHeader("userId");
        String form = lendItemService.commitInvest(userId,investVO);
        return R.ok().data("form",form);
    }

    @PostMapping("notify")
    public  String notifyCommitInvest(HttpServletRequest request){
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, Object> param = RequestHelper.switchMap(parameterMap);
        String lendItemNo = (String) param.get("agentBillNo");
        // 幂等性校验
        boolean exist = transFlowService.isTranExist(lendItemNo);
        //判断为真返回成功
        if (exist){
            return "success";
        }
        lendItemService.notifyCommitInvest(param);
        return "success";
    }

}

